package ck.tool.stocksmart;

import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

public class WatchService extends IntentService {
	InfoGetter m_getter;
	float m_targetPrice;
	float m_currentPrice;
	float m_originPrice;
	int m_refreshTime;
	public WatchService(String name) {
		super(name);
		m_getter = new InfoGetter();
		m_targetPrice = m_getter.getTargetPrice();
		m_refreshTime = m_getter.getRefreshTime();
		m_originPrice = m_getter.getCurrentPrice();
	}
	
	public WatchService() {
		this("demo");
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = android.R.drawable.ic_lock_power_off;
		CharSequence tickerText = "Hello";        
/*
		int delta = intent.getIntExtra("delta", 0);
		SystemClock.sleep(delta);
		long when = System.currentTimeMillis()+delta;
*/
		
		for(;;) {
			long nowTime = System.currentTimeMillis();
			
			if (isTargetReach()) {
				break;
			}
			
			int sleepTime = (int) (m_refreshTime - (System.currentTimeMillis() - nowTime));
			if (sleepTime < 0) {
				sleepTime = 0;
			}
			SystemClock.sleep(sleepTime);
		}
		
		long when = System.currentTimeMillis();
		Notification notification = new Notification(icon, tickerText, when);

		notification.flags |= Notification.FLAG_AUTO_CANCEL;
		Context context = getApplicationContext();
		CharSequence contentTitle = "My notification";
		CharSequence contentText = "Hello World!";
		Intent notificationIntent = new Intent(this, NextActivity.class);

		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);

		mNotificationManager.notify(99, notification);

	}
	
	boolean isTargetReach() {
		m_currentPrice = m_getter.getCurrentPrice();
		if (m_targetPrice > m_originPrice) {
			//increase target
			if (m_currentPrice >= m_targetPrice) {
				return true;
			}
		} else {
			if (m_currentPrice <= m_targetPrice) {
				return true;
			}
		}
		return false;
	}

}
